1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
// app/api/delete-attachment/[id]/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { unlink } from 'fs/promises'
import { join } from 'path'
import db from '@/db/db'
import { vendorEvaluationAttachments, generalEvaluationResponses } from '@/db/schema'
import { eq, and } from 'drizzle-orm'
export async function DELETE(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const attachmentId = parseInt(params.id)
if (isNaN(attachmentId)) {
return NextResponse.json({ error: '유효하지 않은 첨부파일 ID입니다.' }, { status: 400 })
}
// 1. 파일 정보 조회
const [attachment] = await db
.select()
.from(vendorEvaluationAttachments)
.where(
and(
eq(vendorEvaluationAttachments.id, attachmentId),
eq(vendorEvaluationAttachments.isActive, true)
)
)
if (!attachment) {
return NextResponse.json({ error: '첨부파일을 찾을 수 없습니다.' }, { status: 404 })
}
// 2. 실제 파일 삭제
try {
const fullPath = join(process.cwd(), 'public', attachment.filePath)
await unlink(fullPath)
} catch (fileError) {
console.warn('파일 삭제 실패 (파일이 이미 없을 수 있음):', fileError)
// 파일 삭제 실패해도 DB 레코드는 삭제 진행
}
// 3. DB에서 소프트 삭제
await db
.update(vendorEvaluationAttachments)
.set({
isActive: false,
updatedAt: new Date()
})
.where(eq(vendorEvaluationAttachments.id, attachmentId))
// 4. 해당 응답의 첨부파일 상태 업데이트
if (attachment.generalEvaluationResponseId) {
// 남은 활성 첨부파일 개수 확인
const remainingAttachments = await db
.select()
.from(vendorEvaluationAttachments)
.where(
and(
eq(vendorEvaluationAttachments.generalEvaluationResponseId, attachment.generalEvaluationResponseId),
eq(vendorEvaluationAttachments.isActive, true)
)
)
const hasAttachments = remainingAttachments.length > 0
// generalEvaluationResponses 테이블 업데이트
await db
.update(generalEvaluationResponses)
.set({
hasAttachments,
updatedAt: new Date()
})
.where(eq(generalEvaluationResponses.id, attachment.generalEvaluationResponseId))
}
return NextResponse.json({
success: true,
message: '파일이 성공적으로 삭제되었습니다.'
})
} catch (error) {
console.error('파일 삭제 오류:', error)
return NextResponse.json({ error: '파일 삭제에 실패했습니다.' }, { status: 500 })
}
}
|